package cn.gjculture.shopping.api.util;


import cn.gjculture.shopping.api.entity.wx.MessageType;
import cn.gjculture.shopping.api.entity.wx.NewsItem;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MessageHandlerUtil {

    public static Map<String, String> parseXml(HttpServletRequest request) throws Exception {
        Map<String, String> map = new HashMap<>();
        InputStream inputStream = request.getInputStream();
        SAXReader reader = new SAXReader();
        Document document = reader.read(inputStream);
        Element root = document.getRootElement();
        List<Element> elementList = root.elements();
        for (Element e : elementList) {
            System.out.println(e.getName() + "|" + e.getText());
            map.put(e.getName(), e.getText());
        }
        inputStream.close();
        return map;
    }


    public static String buildResponseMessage(Map map) {
        //响应消息
        String responseMessage = "";
        //得到消息类型
        String msgType = map.get("MsgType").toString();
        System.out.println("MsgType:" + msgType);
        //消息类型
        MessageType messageEnumType = MessageType.valueOf(MessageType.class, msgType.toUpperCase());
        switch (messageEnumType) {
            case TEXT:
                //处理文本消息
                responseMessage = handleTextMessage(map);
                break;
            case IMAGE:
                //处理图片消息
                responseMessage = buildNewsMessage(map);
                break;
            case VOICE:
                //处理语音消息
                responseMessage = buildNewsMessage(map);
                break;
            case VIDEO:
                //处理视频消息
                responseMessage = buildNewsMessage(map);
                break;
            case SHORTVIDEO:
                //处理小视频消息
                responseMessage = buildNewsMessage(map);
                break;
            case LOCATION:
                //处理位置消息
                responseMessage = buildNewsMessage(map);
                break;
            case LINK:
                //处理链接消息
                responseMessage = buildNewsMessage(map);
                break;
            case EVENT:
                //处理事件消息,用户在关注与取消关注公众号时，微信会向我们的公众号服务器发送事件消息,开发者接收到事件消息后就可以给用户下发欢迎消息
                responseMessage = handleEventMessage(map);
                break;
            default: responseMessage = buildNewsMessage(map);
                break;
        }
        //返回响应消息
        return responseMessage;

    }

    private static String handleEventMessage(Map map) {
        if ("subscribe".equals(map.get("Event"))||"SCAN".equals(map.get("Event"))) {
            return buildNewsMessage(map);
        }
        return "";
    }

    private static String handleTextMessage(Map map) {
        return buildNewsMessage(map);
    }

    private static String buildTextMessage(Map<String, String> map, String content) {
        //发送方帐号
        String fromUserName = map.get("FromUserName");
        //开发者微信号
        String toUserName = map.get("ToUserName");
        /**
         * 文本消息XML数据格式
         * <xml>
         <ToUserName><![CDATA[toUser]]></ToUserName>
         <FromUserName><![CDATA[fromUser]]></FromUserName>
         <CreateTime>1348831860</CreateTime>
         <MsgType><![CDATA[text]]></MsgType>
         <Content><![CDATA[this is a test]]></Content>
         <MsgId>1234567890123456</MsgId>
         </xml>
         */
        return String.format("<xml>" +
                        "<ToUserName><![CDATA[%s]]></ToUserName>" +
                        "<FromUserName><![CDATA[%s]]></FromUserName>" +
                        "<CreateTime>%s</CreateTime>" +
                        "<MsgType><![CDATA[text]]></MsgType>" +
                        "<Content><![CDATA[%s]]></Content>" +
                        "</xml>",
                fromUserName, toUserName, System.currentTimeMillis(), content);

    }


    private static String buildNewsMessage(Map<String, String> map) {
        String fromUserName = map.get("FromUserName");
        String toUserName = map.get("ToUserName");
        NewsItem item = new NewsItem();
        item.Title = "来买吧 > >";
        item.Description = "";
        item.PicUrl = "http://file.gjculture.cn/static/prod/thumb/b4b84c309a1a4fdda648d920ad3d0c30.jpg";
        item.Url = "https://www.gjculture.cn/app/?code=001Fnj7l1V0Jlo0E6g7l1WAp7l1Fnj7c&state=#/goodDetail?id=c6fef0f7e8434e70845e48de10fc25c6&VNK=70ee7bbb";
        String itemContent1 = buildSingleItem(item);

        NewsItem item2 = new NewsItem();
        item2.Title = "微信开发学习总结（二）——微信开发入门";
        item2.Description = "微信服务器就相当于一个转发服务器，终端（手机、Pad等）发起请求至微信服务器，微信服务器然后将请求转发给我们的应用服务器。应用服务器处理完毕后，将响应数据回发给微信服务器，微信服务器再将具体响应信息回复到微信App终端。";
        item2.PicUrl = "";
        item2.Url = "http://www.cnblogs.com/xdp-gacl/p/5151857.html";
        String itemContent2 = buildSingleItem(item2);
        String content = String.format("<xml>" +
                "<ToUserName><![CDATA[%s]]></ToUserName>" +
                "<FromUserName><![CDATA[%s]]></FromUserName>" +
                "<CreateTime>%s</CreateTime>" +
                "<MsgType><![CDATA[news]]></MsgType>" +
                "<ArticleCount>%s</ArticleCount>" +
                "<Articles>" + "%s" + "</Articles>" +
                "</xml> ", fromUserName, toUserName, System.currentTimeMillis(), 2, itemContent1 + itemContent2);
        return content;

    }


    public static String buildSingleItem(NewsItem item) {
        String itemContent = String.format("<item>" +
                "<Title><![CDATA[%s]]></Title>" +
                "<Description><![CDATA[%s]]></Description>" +
                "<PicUrl><![CDATA[%s]]></PicUrl>" +
                "<Url><![CDATA[%s]]></Url>" +
                "</item>", item.Title, item.Description, item.PicUrl, item.Url);
        return itemContent;
    }



}
